package com.base.lib.base.view

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.launcher.ARouter
import com.gyf.immersionbar.ImmersionBar
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.base.lib.R
import com.base.lib.base.mvvm.view.BaseView
import com.base.lib.base.utils.DensityUtil
import com.base.lib.base.utils.MyMMKV.Companion.mmkv
import com.base.lib.base.utils.NetUtil
import com.base.lib.base.utils.StatusBarUtils
import com.base.lib.base.utils.ext.view.showToast
import com.base.lib.base.widget.LoadingInitView
import com.base.lib.base.widget.LoadingTransView
import com.base.lib.base.widget.NetErrorView
import com.base.lib.base.widget.NoDataView
import com.base.lib.log.KLog

/**
 * 基础页面
 */
abstract class BaseActivity : RxAppCompatActivity(), BaseView {

    companion object {
        val TAG: String = this::class.java.simpleName
    }

    protected lateinit var mContext: BaseActivity

    protected var mNetErrorView: NetErrorView? = null
    protected var mNoDataView: NoDataView? = null
    protected var mLoadingInitView: LoadingInitView? = null
    protected var mLoadingTransView: LoadingTransView? = null

    open lateinit var mContentView: View
    private lateinit var mViewStubContent: ViewStub
    private lateinit var mViewStubInitLoading: ViewStub
    private lateinit var mViewStubTransLoading: ViewStub
    private lateinit var mViewStubNoData: ViewStub
    private lateinit var mViewStubError: ViewStub
    protected var mToolbar: Toolbar? = null
    protected var rl_toolbar: RelativeLayout? = null
    protected var toolbar_title: TextView? = null
    protected var toolbar_left_image_back: TextView? = null
    protected var toolbar_subtitle: TextView? = null
    protected var toolbar_subtitle_image: ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
        val currentTimeMillis = System.currentTimeMillis()
        //0是默认值
        if (mmkv.decodeInt("max_size") == 0) {
            mmkv.encode("max_size", resources.displayMetrics.heightPixels)
        }
        //设置状态栏透明
        setWindowStatusTransparent(this)
        setContentView(R.layout.activity_root)
        mContext = this
        initBundle()
        initCommonView()
        ARouter.getInstance().inject(this)

        initView()
        initListener()

        val totalTime = System.currentTimeMillis() - currentTimeMillis
        KLog.e(TAG, "onCreate: 当前进入的Activity: $localClassName 初始化时间:$totalTime ms")
    }

    open fun initBundle() {
    }

    protected open fun initCommonView() {
        if (enableAllowFullScreen()) {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        mToolbar = findViewById(R.id.toolbar)
        rl_toolbar = findViewById<RelativeLayout>(R.id.rl_toolbar)
        toolbar_title = findViewById<TextView>(R.id.toolbar_title)
        toolbar_left_image_back = findViewById<TextView>(R.id.toolbar_left_image_back)
        toolbar_subtitle = findViewById<TextView>(R.id.toolbar_subtitle)
        toolbar_subtitle_image = findViewById<ImageView>(R.id.toolbar_subtitle_image)

        mViewStubContent = findViewById(R.id.view_stub_content)
        mViewStubInitLoading = findViewById(R.id.view_stub_init_loading)
        mViewStubTransLoading = findViewById(R.id.view_stub_trans_loading)
        mViewStubError = findViewById(R.id.view_stub_error)
        mViewStubNoData = findViewById(R.id.view_stub_nodata)

        initContentView(mViewStubContent)
    }

    open fun initContentView(mViewStubContent: ViewStub) {
        if (onBindLayout() > 0){
            mViewStubContent.layoutResource = onBindLayout()
            mContentView = mViewStubContent.inflate()
        }
    }

    abstract fun onBindLayout(): Int

    abstract fun initView()

    abstract override fun initData()

    override fun initListener() {}

    override fun onStart() {
        super.onStart()
        initData()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun finishActivity() {
        finish()
    }

    open fun enableAllowFullScreen(): Boolean {
        return false
    }

    override fun showInitLoadView() {
        showInitLoadView(true)
    }

    override fun hideInitLoadView() {
        showInitLoadView(false)
    }

    override fun showTransLoadingView() {
        showTransLoadingView(true)
    }

    override fun hideTransLoadingView() {
        showTransLoadingView(false)
    }

    override fun showNoDataView() {
        showNoDataView(true)
    }

    override fun showNoDataView(resid: Int) {
        showNoDataView(true, resid)
    }

    override fun hideNoDataView() {
        showNoDataView(false)
    }

    override fun hideNetWorkErrView() {
        showNetWorkErrView(false)
    }

    override fun showNetWorkErrView() {
        showNetWorkErrView(true)
    }

    open fun showInitLoadView(show: Boolean) {
        if (mLoadingInitView == null) {
            val view = mViewStubInitLoading.inflate()
            mLoadingInitView = view.findViewById(R.id.view_init_loading)
        }
        mLoadingInitView?.visibility = if (show) View.VISIBLE else View.GONE
        mLoadingInitView?.loading(show)
    }


    open fun showNetWorkErrView(show: Boolean) {
        if (mNetErrorView == null) {
            val view = mViewStubError.inflate()
            mNetErrorView = view.findViewById(R.id.view_net_error)
            mNetErrorView?.setOnClickListener(View.OnClickListener {
                if (!NetUtil.checkNetToast()) {
                    return@OnClickListener
                }
                hideNetWorkErrView()
                initData()
            })
        }
        mNetErrorView?.visibility = if (show) View.VISIBLE else View.GONE
    }


    open fun showNoDataView(show: Boolean) {
        if (mNoDataView == null) {
            val view = mViewStubNoData.inflate()
            mNoDataView = view.findViewById(R.id.view_no_data)
        }
        mNoDataView?.visibility = if (show) View.VISIBLE else View.GONE
    }

    open fun showNoDataView(show: Boolean, resid: Int) {
        showNoDataView(show)
        if (show) {
            mNoDataView?.setNoDataView(resid)
        }
    }

    open fun showTransLoadingView(show: Boolean) {
        if (mLoadingTransView == null) {
            val view = mViewStubTransLoading.inflate()
            mLoadingTransView = view.findViewById(R.id.view_trans_loading)
        }
        mLoadingTransView?.visibility = if (show) View.VISIBLE else View.GONE
        mLoadingTransView?.loading(show)
    }

    open fun startActivity(clz: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, clz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    /**
     * 跳转方式
     * 使用方法 startActivity<TargetActivity> { putExtra("param1", "data1") }
     */
    inline fun <reified T> startActivity(block: Intent.() -> Unit) {
        val intent = Intent(this, T::class.java)
        intent.block()
        startActivity(intent)
    }

    /**
     * 阿里路由跳转
     * open("填入你要跳转的ARouter路径") {
     * withString("你要传递extra的key", "你要传递extra的value")
     * }
     */
    open fun open(path: String, block: Postcard.() -> Unit = {}) {
        val postcard = ARouter.getInstance().build(path)
        postcard.block()
        postcard.navigation()
    }

    /**
     * 阿里路由跳转并结束当前页面
     */
    open fun openWithFinish(path: String, block: Postcard.() -> Unit = {}) {
        open(path, block)
        finish()
    }

    private var mLastButterKnifeClickTime: Long = 0

    /**
     * 是否快速点击
     *
     * @return true 是
     */
    open fun beFastClick(): Boolean {
        val currentClickTime = System.currentTimeMillis()
        val flag = currentClickTime - mLastButterKnifeClickTime < 400L
        mLastButterKnifeClickTime = currentClickTime
        return flag
    }

    open fun onClick(v: View?) {

    }

    //沉浸式
    var mBar: ImmersionBar? = null

    fun compatStatusBar(isDarkFont: Boolean) {
        compatStatusBar(isDarkFont, "#ffffff");
    }
    open fun transparentStatusBar(){
        ImmersionBar.with(this).transparentStatusBar().init();
    }
    protected open fun getKeyBoardMode(): Int = -1

    open fun compatStatusBar(isDarkFont: Boolean, color: String?) {
        mBar = ImmersionBar.with(this)
        if (ImmersionBar.isSupportStatusBarDarkFont()) { //判断当前设备支不支持状态栏字体设置为黑色
            mBar?.statusBarColor(color)
        } else {
            mBar?.statusBarColor("#80000000") //状态栏颜色，不写默认透明色
        }
        if (getKeyBoardMode() >= 0) {
            mBar?.keyboardEnable(true)
            mBar?.keyboardMode(getKeyBoardMode())
        }
        //状态栏字体是深色，不写默认为亮色
        mBar?.statusBarDarkFont(isDarkFont)?.navigationBarEnable(false)?.init() //是否可以修改导航栏颜色，默认为true
    }

    open fun compatStatusBar(isDarkFont: Boolean, @ColorRes color: Int) {
        mBar = ImmersionBar.with(this)
        if (ImmersionBar.isSupportStatusBarDarkFont()) {
            mBar?.statusBarColor(color)
        } else {
            mBar?.statusBarColor("#80000000")
        }
        if (getKeyBoardMode() >= 0) {
            mBar?.keyboardEnable(true)
            mBar?.keyboardMode(getKeyBoardMode())
        }
        mBar?.statusBarDarkFont(isDarkFont)?.navigationBarEnable(false)?.init()
    }

    //设置状态栏透明
    fun setWindowStatusTransparent(activity: Activity) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val window: Window = activity.window
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                window.statusBarColor = activity.resources.getColor(R.color.transparent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //5.0以上版本去掉状态栏阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                val decorViewClazz =
                    Class.forName("com.android.internal.policy.DecorView")
                val field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor")
                field.isAccessible = true
                field.setInt(activity.window.decorView, Color.TRANSPARENT) //改为透明
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //设置顶部toolbar相应样式
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    open fun setTop(
        title: String, subTitle: Any? = null,
        isBack: (() -> Unit)? = {
            toolbar_left_image_back?.setBackgroundResource(R.drawable.write_back)
            toolbar_left_image_back?.setOnClickListener { onBackPressed() }
        },
    ): TextView {
        if (toolbar_title == null) toolbar_title = findViewById<TextView>(R.id.toolbar_title)
        mToolbar?.visibility = View.VISIBLE;
        toolbar_title!!.text = title
        toolbar_title!!.isSelected = true
        //小窗模式不计算状态栏的高度
        if (!DensityUtil.isSmallWindow(this)) {
            val layoutParams = mToolbar?.layoutParams
            layoutParams?.height = StatusBarUtils.getStatusBarHeight(this) + DensityUtil.dip2px(this, 46)
            mToolbar?.layoutParams = layoutParams
        }
        //默认显示返回按钮
        isBack?.invoke()
        //根据subtitle的数据类型来显示图片或文字
        when (subTitle) {
            is String -> {
                toolbar_subtitle_image?.visibility = View.GONE
                toolbar_subtitle?.visibility = View.VISIBLE
                toolbar_subtitle?.text = subTitle
            }
            is Int -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.VISIBLE
                toolbar_subtitle_image?.setImageResource(subTitle)
            }
            else -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.GONE
            }
        }
        return toolbar_title as TextView;
    }

    /**
     * 设置状态栏背景色
     */
    open fun setStatusBarBackground(@ColorRes statusBarColor: Int) {
        StatusBarUtils.setStatusBarColor(this,statusBarColor);
    }

    //设置顶部toolbar相应样式
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    open fun setTopTitle(subTitle: Any,clickListener: View.OnClickListener? = null): TextView? {
        mToolbar?.visibility = View.VISIBLE;
        //小窗模式不计算状态栏的高度
        if (!DensityUtil.isSmallWindow(this)) {
            val layoutParams = mToolbar?.layoutParams
            layoutParams?.height =
                StatusBarUtils.getStatusBarHeight(this) + DensityUtil.dip2px(this, 46)
            mToolbar?.layoutParams = layoutParams
        }
        //根据subtitle的数据类型来显示图片或文字
        when (subTitle) {
            is String -> {
                toolbar_title?.background = null;
                toolbar_title?.visibility = View.VISIBLE
                toolbar_title?.text = subTitle
            }
            is Int -> {
                toolbar_title?.visibility = View.VISIBLE
                toolbar_title?.setBackgroundResource(subTitle)
                toolbar_title?.text = ""
            }
            is Drawable -> {
                toolbar_title?.visibility = View.VISIBLE
                toolbar_title?.background = (subTitle)
                toolbar_title?.text = ""
            }
            else -> {
                toolbar_title?.visibility = View.GONE
            }
        }
        toolbar_title?.setOnClickListener(clickListener)
        return toolbar_title;
    }

    //设置顶部toolbar相应样式
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    open fun setRight(subTitle: Any?,clickListener: View.OnClickListener? = null) {
        //根据subtitle的数据类型来显示图片或文字
        when (subTitle) {
            null -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.GONE
            }
            is String -> {
                toolbar_subtitle_image?.visibility = View.GONE
                toolbar_subtitle?.visibility = View.VISIBLE
                toolbar_subtitle?.text = subTitle
            }
            is Int -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.VISIBLE
                toolbar_subtitle_image?.setImageResource(subTitle)
            }
            is Drawable -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.VISIBLE
                toolbar_subtitle_image?.setImageDrawable(subTitle)
            }
            is View.OnClickListener -> {
                rl_toolbar?.setOnClickListener(subTitle)
            }
            else -> {
                toolbar_subtitle?.visibility = View.GONE
                toolbar_subtitle_image?.visibility = View.GONE
            }
        }
        rl_toolbar?.setOnClickListener(clickListener)
    }

    //设置顶部toolbar相应样式
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    open fun setLeft(subTitle: Any?,clickListener: View.OnClickListener? = null) {
        //根据subtitle的数据类型来显示图片或文字
        when (subTitle) {
            null -> {
                toolbar_left_image_back?.visibility = View.GONE
            }
            is String -> {
                toolbar_left_image_back?.background = null;
                toolbar_left_image_back?.visibility = View.VISIBLE
                toolbar_left_image_back?.text = subTitle
            }
            is Int -> {
                toolbar_left_image_back?.visibility = View.VISIBLE
                toolbar_left_image_back?.setBackgroundResource(subTitle)
                toolbar_left_image_back?.text = ""
            }
            is Drawable -> {
                toolbar_left_image_back?.visibility = View.VISIBLE
                toolbar_left_image_back?.background = (subTitle)
                toolbar_left_image_back?.text = ""
            }
            else -> {
                toolbar_left_image_back?.visibility = View.GONE
            }
        }
        toolbar_left_image_back?.setOnClickListener(clickListener)
    }


    protected fun toast(s: String) {
        s.showToast()
    }
}
